package com.gitee.leijin.rbac.security;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.gitee.leijin.rbac.model.TokenDTO;
import com.gitee.leijin.rbac.service.CacheManager;
import com.gitee.leijin.rbac.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;


@Slf4j
public class AuthFilter extends OncePerRequestFilter {

    private final CacheManager cacheManager;

    public AuthFilter(CacheManager cacheManager) {
        this.cacheManager = cacheManager;
    }


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        log.info("request uri {}", request.getRequestURI());
        String token = request.getHeader(HttpHeaders.AUTHORIZATION);
        if (token == null) {
            // 把授权的控制交给 FilterSecurityInterceptor
            filterChain.doFilter(request, response);
            return;
        }
        DecodedJWT decodedJWT = JwtUtils.verify(token);
        TokenDTO tokenDTO = JwtUtils.parse(decodedJWT, TokenDTO.class);
        if (tokenDTO == null) {
            filterChain.doFilter(request, response);
            return;
        }
        SecurityContextHolder.getContext().setAuthentication(buildAuthentication(tokenDTO));
        filterChain.doFilter(request, response);
    }

    private Authentication buildAuthentication(TokenDTO tokenDTO) {
        SecurityUser securityUser = cacheManager.get(String.valueOf(tokenDTO.getUserId()), SecurityUser.class);
        if (securityUser == null) {
            return null;
        }
        Collection<? extends GrantedAuthority> authorities = securityUser.getAuthorities();
        return new UsernamePasswordAuthenticationToken(securityUser, null, authorities);
    }

}
